package work.comeback.omo.dao.user.imp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import work.comeback.omo.dao.user.IUser;
import work.comeback.omo.model.user.UserBean;
import work.comeback.omo.model.user.UserSql;
import work.comeback.omo.util.configuration.Application;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class UserImpl implements IUser {
    private static final Logger logger = LoggerFactory.getLogger(UserImpl.class);
    private static final Application application = Application.getInstance();
    private final Connection connection;

    public UserImpl() {
        this(application.getConnection());
    }

    public UserImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public UserBean findUserByID(int id) {
        String sql = UserSql.FIND_USER_BY_ID;
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setInt(1, id);
            return getUser(stmt);
        } catch (SQLException e) {
            logger.error("Error finding user by ID: {}", e.getMessage(), e);
        }
        return null;
    }

    private UserBean getUser(ResultSet rs) throws SQLException {
        UserBean user = new UserBean();
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setRole(rs.getString("role"));
        user.setAvatarUrl(rs.getString("avatar_url"));
        user.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
        user.setUpdatedAt(rs.getTimestamp("updated_at").toLocalDateTime());
        return user;
    }

    private UserBean getUser(PreparedStatement stmt) throws SQLException {
        try (ResultSet rs = stmt.executeQuery()) {
            if (rs.next()) {
                return getUser(rs);
            }
        }
        return null;
    }

    @Override
    public UserBean findUserByUsername(String username) {
        String sql = UserSql.FIND_USER_BY_USERNAME;
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, username);
            return getUser(stmt);
        } catch (SQLException e) {
            logger.error("Error finding user by username: {}", e.getMessage(), e);
        }
        return null;
    }

    @Override
    public List<UserBean> findByRole(String role) {
        List<UserBean> users = new ArrayList<>();
        String sql = UserSql.FIND_USERS_BY_ROLE;
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, role);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    UserBean user = getUser(rs);
                    users.add(user);
                }
            }
        } catch (SQLException e) {
            logger.error("Error finding users by role: {}", e.getMessage(), e);
        }
        return users;
    }

    @Override
    public void deleteUser(UserBean user) {
        String sql = UserSql.DELETE_USER;
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setInt(1, user.getId());
            stmt.executeUpdate();
        } catch (SQLException e) {
            logger.error("Error deleting user: {}", e.getMessage(), e);
        }
    }

    @Override
    public void updateUser(UserBean user) {
        String sql = UserSql.UPDATE_USER;
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            stmt.setString(3, user.getRole());
            stmt.setString(4, user.getAvatarUrl());

            // 如果没有传递更新日期，则使用当前时间
            if (user.getUpdatedAt() == null) {
                user.setUpdatedAt(LocalDateTime.now()); // 使用当前时间
            }

            stmt.setTimestamp(5, Timestamp.valueOf(user.getUpdatedAt()));
            stmt.setInt(6, user.getId());
            stmt.executeUpdate();
        } catch (SQLException e) {
            logger.error("Error updating user: {}", e.getMessage(), e);
        }
    }

    @Override
    public void createUser(UserBean user) {
        String sql = UserSql.INSERT_USER;
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            stmt.setString(3, user.getRole());
            stmt.setString(4, user.getAvatarUrl());

            // 如果没有传递时间，则使用当前时间
            if (user.getCreatedAt() == null) {
                user.setCreatedAt(LocalDateTime.now()); // 使用当前时间
            }
            if (user.getUpdatedAt() == null) {
                user.setUpdatedAt(LocalDateTime.now()); // 使用当前时间
            }

            stmt.setTimestamp(5, Timestamp.valueOf(user.getCreatedAt()));
            stmt.setTimestamp(6, Timestamp.valueOf(user.getUpdatedAt()));

            stmt.executeUpdate();
        } catch (SQLException e) {
            logger.error("Error creating user: {}", e.getMessage(), e);
        }
    }
}